package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
/**
 * spu信息
 */
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired SkuInfoService skuInfoService;
    @Autowired SkuImagesService skuImagesService;
    @Autowired SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired CouponFeignService couponFeignService;
    @Autowired SpuInfoDescService spuInfoDescService;
    @Autowired SpuImagesService spuImagesService;
    @Autowired AttrService attrService;
    @Autowired ProductAttrValueService productAttrValueService;
    @Autowired BrandService brandService;
    @Autowired CategoryService categoryService;
    @Autowired WareFeignService wareFeignService;
    @Autowired SearchFeignService searchFeignService;

    /**
     * 根据 skuId 查询 spu 信息
     */
    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        //1、根据 skuId 查询 sku 信息
        SkuInfoEntity entity = skuInfoService.getById(skuId);
        //2、从 sku信息 里面获取 spuId
        Long spuId = entity.getSpuId();
        //3、再根据 spuId 查询 spu 信息
        SpuInfoEntity spuInfoEntity = getById(spuId);
        return spuInfoEntity;
    }


    /**
     * 商品上架功能
     */
    @Override
    public void up(Long spuId) {
        //1、查出当前 spuId 对应的所有 sku信息，品牌名称
        List<SkuInfoEntity> skus = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        //2.4 查询当前sku的所有可以被用来检索的规格属性
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.list(
                new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<Long> attrIds = baseAttrs.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);    //调用《在指定的属性集合中，找出要检索的属性的id》方法

        Set<Long> idSet = new HashSet<>(searchAttrIds);    //转成set集合

        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());    //判断 idSet 里面是否包含 AttrId
        }).map(item -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());

        //2.1 远程调用，查询库存系统是否有库存
        Map<Long, Boolean> stockMap = null;
        try {
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {};
            R r = wareFeignService.getSkusHanStock(skuIdList);    //调用《根据skuId查询库存》方法
            stockMap = r.getData(typeReference)    //传入 typeReference 利用 fastjson 进行逆转
                    .stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        }catch (Exception ex){
            log.error("库存查询出现异常, 原因: {}", ex);
        }

        //2、封装每个sku信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upProducts = skus.stream().map(sku -> {
            //用来封装需要的数据
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, esModel);

            //单独处理 SkuInfoEntity 和 SkuEsModel 表中，他们属性不一样的或者不是共同拥有的属性
            //skuPrice  skuImg  hasStock  hotScore  attrId  attrName  attrValue  catalogName  attrs  brandImg  brandName
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());

            //2.1 远程调用，查询库存系统是否有库存
            if (finalStockMap == null){
                esModel.setHasStock(true);
            }else {
                esModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }

            //2.2 热度评分, TODO
            esModel.setHotScore(0L);

            //2.3 查询品牌和分类的名字
            BrandEntity brand = brandService.getById(esModel.getBrandId());    //品牌
            esModel.setBrandName(brand.getName());
            esModel.setBrandImg(brand.getLogo());

            CategoryEntity category = categoryService.getById(esModel.getCatalogId());    //分类
            esModel.setCatalogName(category.getName());

            //2.4 设置需要检索的属性
            esModel.setAttrs(attrsList);

            return esModel;
        }).collect(Collectors.toList());

        //3、远程调用，将数据发给es进行保存: gulimall-search
        R r = searchFeignService.productStatusUp(upProducts);    //远程调用《保存数据到es》方法
        if (r.getCode() == 0){
            //远程调用成功，修改当前spu状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());    //调用《根据 spuId 修改 spu 状态》方法
        }else {
            //远程调用失败
            //TODO, 重复调用，接口幂等性，重试机制等问题？以后再解决
        }
    }


    /**
     * spu检索 (查询功能)
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){    //如果不为空或者不为0，equalsIgnoreCase：忽略大小写
            wrapper.eq("catalog_id", catelogId);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){    //如果不为空或者不为0，equalsIgnoreCase：忽略大小写
            wrapper.eq("brand_id", brandId);
        }

        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status", status);
        }

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and((w) -> {
                w.eq("id", key).or().like("spu_name", key);
            });}

        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }


    /**
     * 保存商品
     * TODO 其他问题高级篇再完善
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1、保存spu基本信息`pms_spu_info`
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.save(infoEntity);

        //2、保存spu的描述图片`pms_spu_info_desc`
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(infoEntity.getId());    //商品id
        descEntity.setDecript(String.join(",", decript));    //商品介绍
        spuInfoDescService.save(descEntity);

        //3、保存spu的图片集`pms_spu_images`
        List<String> images = vo.getImages();
        if (images != null && images.size() != 0) {
            List<SpuImagesEntity> collect = images.stream().map(image -> {
                SpuImagesEntity imagesEntity = new SpuImagesEntity();
                imagesEntity.setSpuId(infoEntity.getId());
                imagesEntity.setImgUrl(image);    //图片地址
                return imagesEntity;
            }).collect(Collectors.toList());
            spuImagesService.saveBatch(collect);
        }

        //4、保存spu的规格参数`pms_product_attr_value`
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntityList = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(attrEntity.getAttrName());    //属性名
            valueEntity.setAttrValue(attr.getAttrValues());    //属性值
            valueEntity.setQuickShow(attr.getShowDesc());    //快速展示【是否展示在介绍上；0-否 1-是】
            valueEntity.setSpuId(infoEntity.getId());
            return valueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntityList);

        //5、保存spu的积分信息`gulimall_sms`->`sms_spu_bounds`
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(infoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);    //远程调用 《保存spu的积分信息》方法
        if (r.getCode() != 0){
            log.error("远程保存spu积分信息失败");
        }

        //6、保存spu对应的所有sku信息
        List<Skus> skus = vo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(item -> {
                String defaultImg = "";
                //查找出默认图片
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }}
                //6.1、sku的基本信息`pms_sku_info`
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setSpuId(infoEntity.getId());
                skuInfoEntity.setBrandId(infoEntity.getBrandId());    //品牌id
                skuInfoEntity.setCatalogId(infoEntity.getCatalogId());    //所属分类id
                skuInfoEntity.setSaleCount(0L);    //销量
                skuInfoEntity.setSkuDefaultImg(defaultImg);    //默认图片
                skuInfoService.save(skuInfoEntity);

                //6.2、sku的图片信息`pms_sku_images`
                Long skuId = skuInfoEntity.getSkuId();

                List<SkuImagesEntity> skuImagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());    //图片地址
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());    //默认图[0 - 不是默认图，1 - 是默认图]
                    return skuImagesEntity;
                }).filter(entity -> {
                    return StringUtils.isNotBlank(entity.getImgUrl());    //如果返回 true 就是需要，false 就是剔除
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);

                //6.3、sku的销售属性信息`pms_sku_sale_attr_value`
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                //6.4、sku的优惠、满减等信息`gulimall_sms`->`sms_sku_ladder`/`sms_sku_full_reduction`/`sms_member_price`
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(infoEntity.getId());
                //如果 满几件 大于0 或者 满多少元 大于0等于1，才远程调用《保存sku的优惠、满减等信息》方法
                if(skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1){
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0){
                        log.error("远程保存优惠信息失败");
                    }}});}}


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );
        return new PageUtils(page);
    }
}